<template>
  <div>
    <a href="#/home">首页</a><br />
    <a href="#/music">音乐</a><br />
    <a href="#/movie">电影</a><br />
    <a href="#/about">关于</a>
    <keep-alive>
      <component :is="name"></component>
    </keep-alive>
  </div>
</template>

<script>
// 导入组件
import MyAbout from './components/MyAbout.vue'
import MyHome from './components/MyHome.vue'
import MyMovie from './components/MyMovie.vue'
import MyMusic from './components/MyMusic.vue'
export default {
  // 注册组件
  components: { MyAbout, MyHome, MyMovie, MyMusic },
  data () {
    return {
      name: 'MyHome'
    }
  },
  // 写到 created 生命周期函数中，这样，代码可以自动执行
  created () {
    // 注册window的hashchange事件，当hash地址改变的时候，就会触发 hashchange 事件
    // 这个事件处理函数要使用箭头函数
    window.addEventListener('hashchange', () => {
      const hash = location.hash
      if (hash === '#/home') {
        this.name = MyHome //首页
      } else if (hash === '#/music') {
        this.name = MyMusic //音乐
      } else if (hash === '#/movie') {
        this.name = MyMovie //电影
      } else if (hash === '#/about') {
        this.name = MyAbout //关于
      }
    })
  }
}
</script>

<style></style>
